<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\EpayCore;
use app\common\library\Wechat;
use app\common\model\MoneyLog;
use app\common\model\pay\Order;
use app\common\model\task\Lists;
use app\common\model\task\Userlog;
use app\common\model\User;
use think\Db;
use think\Exception;

class Notify extends Api
{
    protected $noNeedLogin = "*";
    protected $noNeedRight = "*";

    public function juhe()
    {
        $epay = new EpayCore([
            "pid" => "1402",
            "apiurl" => "https://pays.shenghaihao.com/",
            "key" => "mDC1IteMZm00EMCQ100CdcezVvDcskqs"
        ]);

        $verify_result = $epay->verifyNotify();
        if ($verify_result) {//验证成功
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];
            $order = Order::where(['order_sn' => $out_trade_no, 'status' => 0])->find();
            if (!$order) {
                echo "fail";
                die();
            }
            //彩虹易支付交易号
            $trade_no = $_GET['trade_no'];

            //交易状态
            $trade_status = $_GET['trade_status'];

            //支付方式
            $type = $_GET['type'];

            //支付金额
            $money = $_GET['money'];

            Db::startTrans();
            try {
                if ($_GET['trade_status'] == 'TRADE_SUCCESS') {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    $order->status = 1;
                    \app\common\model\User::money($order->money, $order->user_id, '用户充值', 2);
                    $task_list = Lists::where(['location' => 'topup', 'switch' => 1])->select();
                    foreach ($task_list as $value) {
                        if ($order->price >= $value['standard_limit']) {
                            $status = Userlog::check($value, $order->user_id);
                            if ($status == -1) {
                                Userlog::get_task($value['id'], $order->user_id, 0, 1);
                            }
                        }
                    }
                } else {
                    $order->status = -1;
                    $order->desc = isset($_GET['param']) ?? "";
                }
                $order->save();
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                //验证失败
                echo "fail";
                die();
            }

            //验证成功返回
            echo "success";
        } else {
            //验证失败
            echo "fail";
        }
    }

    public function wechat_pay()
    {
        $app = Wechat::app();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
//            $order = 查询订单($message['out_trade_no']);
            $order = Order::where(['order_sn' => $message['out_trade_no'], 'status' => 0])->find();

            if (!$order) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                Db::startTrans();
                try {
                    // 用户是否支付成功
                    if (array_get($message, 'result_code') === 'SUCCESS') {
                        $order->status = 1;
                        \app\common\model\User::money($order->money, $order->user_id, '用户充值', 2);
                    } elseif (array_get($message, 'result_code') === 'FAIL') {
                        $order->status = -1;
                        $order->desc = $message['return_msg'];
                    }
                    $order->save();
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });
        $response->send();
    }

    public function ali_pay()
    {
        return 1;
    }
}